﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.Devices.Sensors;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;

namespace Compass
{
    partial class MainPage
    {
        private Windows.Devices.Sensors.Compass _compass;
        private Exception _lastException;
        private double? _lastHeading;

        public MainPage()
        {
            InitializeComponent();
            _compass = Windows.Devices.Sensors.Compass.GetDefault();
            if (_compass != null)
            {
                _compass.ReportInterval = Math.Max(100, _compass.MinimumReportInterval);
                _compass.ReadingChanged += new TypedEventHandler<Windows.Devices.Sensors.Compass, CompassReadingChangedEventArgs>(_compass_ReadingChanged);
            }
            else
            {
                Heading.Text = "Could not get heading. (no compass)";
            }

            var transform = new CompositeTransform();
            transform.CenterX = HeadingImage.Width / 2;
            transform.CenterY = HeadingImage.Width / 2;
            HeadingImage.RenderTransform = transform;
        }

        void _compass_ReadingChanged(Windows.Devices.Sensors.Compass sender, CompassReadingChangedEventArgs args)
        {
            _lastException = null;
            try
            {
                if (_compass == null)
                {
                    throw new Exception("Could not get heading. (no compass)");
                }
                var heading = args.Reading.HeadingMagneticNorth;

                _lastHeading = heading;
                this.Dispatcher.Invoke(CoreDispatcherPriority.Normal, invokeHandler, sender, null);
            }
            catch (Exception ex)
            {
                _lastException = ex;
                this.Dispatcher.Invoke(CoreDispatcherPriority.Normal, invokeHandler, sender, null);
            }
        }

        private void invokeHandler(object sender, InvokedHandlerArgs e)
        {
            if (_lastException != null)
            {
                Heading.Text = _lastException.Message;
                return;
            }

            if (_lastHeading != null)
            {
                Heading.Text = _lastHeading.Value.ToString("0.0");
                ((CompositeTransform)HeadingImage.RenderTransform).Rotation = -_lastHeading.Value;
                return;
            }

            Heading.Text = "Could not get heading (unknown)";
        }
    }
}
